﻿#region Using Statements
using System.IO;
using System.IO.Compression;
#endregion

namespace DirectZZT.Shared.Core
{
    /// <summary>
    /// Provides GZip compression algorithm.
    /// </summary>
    [Export("GZip", Type = typeof(ICompression))]
    public sealed class CompressionGzip : ICompression
    {

        #region Constructors

        /// <summary>
        /// Initializes a new instance of the CompressionGzip class.
        /// </summary>
        public CompressionGzip()
        {

        }

        #endregion

        #region ICompression Members

        /// <summary>
        /// Compresses the <paramref name="data"/> buffer.
        /// </summary>
        /// <param name="data"></param>
        /// <returns>The compressed buffer.</returns>
        public byte[] Compress(byte[] data)
        {
            MemoryStream input = new MemoryStream(data);
            MemoryStream output = new MemoryStream();
            using (GZipStream compress = new GZipStream(output, CompressionMode.Compress))
            {
                // TODO: looks ugly... use default approach from MSDN here!
                byte[] buffer = new byte[4096];
                int numRead;
                while ((numRead = input.Read(buffer, 0, buffer.Length)) != 0)
                {
                    compress.Write(buffer, 0, numRead);
                }
            }
            return output.ToArray();
        }

        /// <summary>
        /// Uncompresses the <paramref name="data"/> buffer.
        /// </summary>
        /// <param name="data"></param>
        /// <returns>The uncompressed buffer.</returns>
        public byte[] Decompress(byte[] fi)
        {
            MemoryStream ms = new MemoryStream();
            // Get the stream of the source file.
            using (MemoryStream inFile = new MemoryStream(fi))
            {
                using (GZipStream Decompress = new GZipStream(inFile, CompressionMode.Decompress))
                {
                    //Copy the decompression stream into the output file.
                    // TODO: looks ugly... use default approach from MSDN here!
                    byte[] buffer = new byte[4096];
                    int numRead;
                    while ((numRead = Decompress.Read(buffer, 0, buffer.Length)) != 0)
                    {
                        ms.Write(buffer, 0, numRead);
                    }
                }
            }
            return ms.ToArray();
        }

        #endregion

    }
}
